﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace Helper
{
   public  class DatasetTools
    {
        //Сформировать список на List<T> на основе DataSet
        public static DataSet ConvertDatasetToList<T>(IList<T> list)
        {
            Type elementType = typeof(T);
            DataSet ds = new DataSet();
            DataTable t = new DataTable();
            ds.Tables.Add(t);

            //add a column to table for each public property on T
            foreach (var propInfo in elementType.GetProperties())
            {
                Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

                t.Columns.Add(propInfo.Name, ColType);
            }

            //go through each property on T and add each value to the table
            foreach (T item in list)
            {
                DataRow row = t.NewRow();

                foreach (var propInfo in elementType.GetProperties())
                {
                    row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                }

                t.Rows.Add(row);
            }

            return ds;
        }

       /// <summary>
       /// Конвертнуть табличку с индексом 0 в List<T>
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="DS"></param>
       /// <param name="result"></param>
       public static void   ConvertFistTableToGenericList<T>(DataSet ds, ref List<T> result)
       {
           if (ds.Tables.Count == 0)
               return;

           Type elementType = typeof(T);           
           DataTable t = ds.Tables [0];

           foreach (DataRow rw in t.Rows)
           {
               
               var itm = Activator.CreateInstance(elementType);               
               foreach (var propInfo in elementType.GetProperties())
               {
                   if (t.Columns[propInfo.Name] == null)
                       continue;

                   try
                   {
                       propInfo.SetValue(itm, rw[propInfo.Name], null);
                   }
                   //убиваем ошибку присваивания.
                   catch 
                   {
                   }
               }
               result.Add((T)itm);
           }

       }

        public static DataSet convertDataReaderToDataSet(SqlDataReader reader)
        {
            DataSet dataSet = new DataSet();
            do
            {
                // Create new data table

                DataTable schemaTable = reader.GetSchemaTable();
                DataTable dataTable = new DataTable();

                if (schemaTable != null)
                {
                    // A query returning records was executed

                    for (int i = 0; i < schemaTable.Rows.Count; i++)
                    {
                        DataRow dataRow = schemaTable.Rows[i];
                        // Create a column name that is unique in the data table
                        string columnName = (string)dataRow["ColumnName"]; //+ "<C" + i + "/>";
                        // Add the column definition to the data table
                        DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
                        dataTable.Columns.Add(column);
                    }

                    dataSet.Tables.Add(dataTable);

                    // Fill the data table we just created

                    while (reader.Read())
                    {
                        DataRow dataRow = dataTable.NewRow();

                        for (int i = 0; i < reader.FieldCount; i++)
                            dataRow[i] = reader.GetValue(i);

                        dataTable.Rows.Add(dataRow);
                    }
                }
                else
                {
                    // No records were returned

                    DataColumn column = new DataColumn("RowsAffected");
                    dataTable.Columns.Add(column);
                    dataSet.Tables.Add(dataTable);
                    DataRow dataRow = dataTable.NewRow();
                    dataRow[0] = reader.RecordsAffected;
                    dataTable.Rows.Add(dataRow);
                }
            }
            while (reader.NextResult());
            return dataSet;
        }

        //public static DataSet convertOraDataReaderToDataSet(OracleDataReader reader)
        //{
        //    DataSet dataSet = new DataSet();
        //    do
        //    {
        //        // Create new data table

        //        DataTable schemaTable = reader.GetSchemaTable();
        //        DataTable dataTable = new DataTable();

        //        if (schemaTable != null)
        //        {
        //            // A query returning records was executed

        //            for (int i = 0; i < schemaTable.Rows.Count; i++)
        //            {
        //                DataRow dataRow = schemaTable.Rows[i];
        //                // Create a column name that is unique in the data table
        //                string columnName = (string)dataRow["ColumnName"]; //+ "<C" + i + "/>";
        //                // Add the column definition to the data table
        //                DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
        //                dataTable.Columns.Add(column);
        //            }

        //            dataSet.Tables.Add(dataTable);

        //            // Fill the data table we just created

        //            while (reader.Read())
        //            {
        //                DataRow dataRow = dataTable.NewRow();

        //                for (int i = 0; i < reader.FieldCount; i++)
        //                    dataRow[i] = reader.GetValue(i);

        //                dataTable.Rows.Add(dataRow);
        //            }
        //        }
        //        else
        //        {
        //            // No records were returned

        //            DataColumn column = new DataColumn("RowsAffected");
        //            dataTable.Columns.Add(column);
        //            dataSet.Tables.Add(dataTable);
        //            DataRow dataRow = dataTable.NewRow();
        //            dataRow[0] = reader.RecordsAffected;
        //            dataTable.Rows.Add(dataRow);
        //        }
        //    }
        //    while (reader.NextResult());
        //    return dataSet;
        //}


        public static string convertTableToJSONString(DataTable Dt)
        {

            string[] StrDc = new string[Dt.Columns.Count];
            string HeadStr = string.Empty;

            //for (int i = 0; i < Dt.Columns.Count; i++)
            for (int i = 0; i < Dt.Columns.Count; i++)
            {

                StrDc[i] = Dt.Columns[i].Caption;

                HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
            }

            HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);

            StringBuilder Sb = new StringBuilder();
            //Sb.Append("{\"" + Dt.TableName + "\" : [");
            Sb.Append("[");
            string v = string.Empty;
            //for (int i = 0; i < Dt.Rows.Count; i++)            
            for (int i = 0; i < Dt.Rows.Count; i++)            
            {

                string TempStr = HeadStr;
                Sb.Append("{");

                for (int j = 0; j < Dt.Columns.Count; j++)
                {

                    v=Dt.Rows[i][j].ToString();
                    v = v.Replace(@"/", string.Empty);
                    v = v.Replace(@"~", string.Empty);
                    v = v.Replace(@":", string.Empty);
                    v = v.Replace(@"{", string.Empty);
                    v = v.Replace(@"}", string.Empty);
                    v = v.Replace("\"", string.Empty);

                    TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", v);
                }

                Sb.Append(TempStr + "},");
            }

            Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
            Sb.Append("]");

            return Sb.ToString();
        }
    }
}
